package scuba.DiveBuddy;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import scuba.DiveBuddy.Class.AirMix;
import scuba.DiveBuddy.Core.Toolbelt;
import scuba.DiveBuddy.Core.Tuple;

/**
 * @author Alex Anderson
 * @version 1.0
 * @since {27/02/14}
 */
public class AirMixBuilderActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_airmixbuilder);
    }


    private void CommitMix() {
        String name = ((EditText)findViewById(R.id.airMixName)).getText().toString();

        Tuple<Boolean, Float> O2result = Toolbelt.Toolkit.getFloatFromString(
                ((EditText)findViewById(R.id.airMixO2)).getText().toString(), 0);
        if(!O2result.x) { //throw an error
            Toolbelt.Toolkit.showToast(getApplicationContext(), "Invalid O2%");
        }

        Tuple<Boolean, Float> Nresult = Toolbelt.Toolkit.getFloatFromString(
                ((EditText)findViewById(R.id.airMixN)).getText().toString(), 0);
        if(!Nresult.x) { //throw an error
            Toolbelt.Toolkit.showToast(getApplicationContext(), "Invalid N%");
        }

        Tuple<Boolean, Float> Hresult = Toolbelt.Toolkit.getFloatFromString(
                ((EditText)findViewById(R.id.airMixH)).getText().toString(), 0);
        if(!Hresult.x) { //throw an error
            Toolbelt.Toolkit.showToast(getApplicationContext(), "Invalid H%");
        }

        int sum = Math.round(O2result.y + Nresult.y + Hresult.y);

        if(sum != 100) {
            Toolbelt.Toolkit.showToast(getApplicationContext(), "Mix must make 100%");
            return;
        }

        //todo: commit the mix to the database
        Boolean created = AirMix.CreateMix(name, O2result.y, Nresult.y, Hresult.y);
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()) {
            default: break;

            case R.id.action_create:
                this.CommitMix();
                break;

            case R.id.action_cancel:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.savecancel_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }
}